package slice

import "sort"

func Remove[T any](slice []T, index int) ([]T, error) {
	slen := len(slice)

	if index >= slen {
		return slice, ErrIndexOutOfBounds
	}

	if index+1 < slen {
		copy(slice[index:], slice[index+1:])
	}
	slice = slice[:slen-1]

	// shrink if the current len is half of the capacity
	if 2*len(slice) <= cap(slice) {
		newSlice := make([]T, len(slice))
		copy(newSlice[:], slice[:])
		slice = newSlice
	}

	return slice, nil
}

func RemoveMany[T any](slice []T, indexes ...int) ([]T, error) {
	sort.Ints(indexes)

	for _, i := range indexes {
		if i >= len(slice) {
			return slice, ErrIndexOutOfBounds
		}
	}

	for i, idx := range indexes {
		// the real index changes while we keep removing item from the slice
		newSlice, err := Remove(slice, idx-i)
		if err != nil {
			return newSlice, err
		}
		slice = newSlice
	}

	return slice, nil
}
